package homework1;

import java.util.Random;

public class GenerateExpression extends Thread{

	Expression expression;
	
	public GenerateExpression(Expression exp) {
		this.expression = exp;
	}
	
	public void generateExp() {
		String[] ops = {"+", "-", "*", "/"};
		Random rd = new Random();
		int times = rd.nextInt(3) + 1;
		int[] numbers = new int[times + 1];
		String[] operators = new String[times];
		for (int i = 0; i < operators.length; i++) {
			operators[i] = ops[rd.nextInt(ops.length)];
		}
		for (int i = 0; i < numbers.length; i++) {
			numbers[i] = rd.nextInt(100) + 1;
		}
		for (int i = 0; i < numbers.length; i++) {
			expression.expr = expression.expr.concat(String.valueOf(numbers[i]));
			if (i < operators.length) {
				expression.expr = expression.expr.concat(operators[i]);
			}
		}
	}
	
	public void run() {
		for (int i = 0; i < 100; i++) {
			synchronized(expression) {
				if (!expression.expr.equals("")) {
					try {
						expression.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				generateExp();
				expression.notify();
			}
		}
	}
}
